﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Collections;
using System.Threading;



namespace Serialportsimulator
{

    public enum Framestatus : int
    {
        nodata = 0,
        intactframe = 1,
        excessframe = 2,
        lackframe = 3
    }


    public partial class MCUsimulator : Form
    {
        public static ArrayList stagingframe = new ArrayList();

        SerialPort spSend;   //用虚拟接口发送和接收数据
        SerialPort spReceive;
        public delegate void listviewdata(string text);//委托
        public listviewdata updatelistview;
        SerialPort serialPort1 = null;
        string Comname = null;
        Framestatus framestatus = Framestatus.nodata;
        static bool LackFrameLength = false;
        int frameCount = 0;
        const char START_BYTE = '#';
        const char STOP_BYTE  = '@';

        DAO database;
        public MCUsimulator()
        {

            InitializeComponent();
            updatelistview = new listviewdata(Updatelistview);//实例化委托对象
            this.FormClosing += new FormClosingEventHandler(MCUsimulator_FormClosing);
            ResponseModel.Visible = false;
            //serialPort1.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
            //检查是否含有串口  
            string[] str = SerialPort.GetPortNames();
            if (str == null)
            {
                MessageBox.Show("本机没有串口！", "Error");
                return;
            }

            //添加串口项目  
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口  
                SerialportName.Items.Add(s);
                //串口设置默认选择项  
                SerialportName.SelectedIndex = 0;         //设置SerialportName的默认选项 
            }

            database = new DAO();

        }

        private void Cleardata_Click(object sender, EventArgs e)
        {
            PortDataView.Items.Clear();
        }

        private void Open_ClosePort_Click(object sender, EventArgs e)
        {
            string text = Open_ClosePort.Text;
            if (null == serialPort1)
            {
                serialPort1 = new SerialPort(Comname, 115200, Parity.None, 8, StopBits.One);
            }
            if (Open_ClosePort.Text == "启动")
            {                
                try
                {
                    serialPort1.Open();
                    MessageBox.Show("串口启动成功");
                    serialPort1.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);
                    Open_ClosePort.Text = "停止";
                    SerialportName.Enabled = false;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("串口启动失败");
                }

            }
            else
            {
                SerialportName.Enabled = true;
                serialPort1.DataReceived -= null;
                serialPort1.Close();
                Open_ClosePort.Text = "启动";
            }
        }

        private void PortDataView_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void SerialportName_SelectedIndexChanged(object sender, EventArgs e)
        {
            Comname = SerialportName.SelectedItem.ToString();
        }

        private void MCUsimulator_Load(object sender, EventArgs e)
        {

        }
        private void MCUsimulator_FormClosing(object sender, FormClosingEventArgs e)
        {
            SerialPort port = new SerialPort();
            DialogResult dr;
            dr = MessageBox.Show("确定要退出吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                port.Close();
                e.Cancel = false; ;
            }
            else
            {
                e.Cancel = true;
            }

        }

        public static void ExtractFramedata(ArrayList IntactFrame, int framelength, byte[] bytes, out int status, out ArrayList Frame)
        {
            status = 0;
            Frame = new ArrayList();

        }

        void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string frameString = String.Empty;
            while (serialPort1.BytesToRead != 0 || framestatus != Framestatus.nodata)
            {
                int count = serialPort1.BytesToRead;
                byte[] readBuffer = new byte[count];
                //读取串口字节
                serialPort1.Read(readBuffer, 0, count);
                string converted = System.Text.Encoding.Default.GetString(readBuffer);
                //帧解析
                foreach (char data in converted)
                {
                    if (data == START_BYTE)
                    {
                        framestatus = Framestatus.lackframe;
                    }
                    else if (data == STOP_BYTE)
                    {
                        framestatus = Framestatus.intactframe;
                        // 输出显示, 存储
                        HandleFrame(frameString);
                        frameString = String.Empty;
                    }
                    else
                    {
                        frameString += data;
                    }
                }

                if (framestatus == Framestatus.intactframe)
                {
                    framestatus = Framestatus.nodata;
                }
            }
           
        }

        // 处理完整帧
        private void HandleFrame(string frameString)
        {
            frameCount++;
            this.Invoke(updatelistview, frameString);
            //写入数据库
            database.SaveRecord(frameString);
        }


        //显示数据
        public void Updatelistview(string text)
        {
            this.PortDataView.BeginUpdate();   //数据更新，
            ListViewItem lvi = new ListViewItem();
            lvi.Text = frameCount.ToString();
            lvi.SubItems.Add(text);
            this.PortDataView.Items.Add(lvi);
            this.PortDataView.EndUpdate();  //结束数据处理，UI界面一次性绘制。

        }
    }
}
